package com.ict.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;



import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;

public class MQTopicPublish{

    private static String IP,user,password,EXCHANGE_NAME;
    private static String EXCHANGE_TYPE = "topic";
    private static boolean EXCHANGE_DURABLE = true;
    private static int  Port = 0;

    private static Connection connection;
    private static Channel channel;

    public MQTopicPublish(String IP,String user,String password,String EXCHANGE_NAME,int port){
        this.IP = IP;
        this.user = user;
        this.password = password;
        this.EXCHANGE_NAME = EXCHANGE_NAME;
        this.Port=port;

        BaseConnection();
    }

    /**
     * 发布消息
     * @param messages
     */
    public void Publish(List<MessageStruct> messages){

        for(MessageStruct severity:messages){

            try {
                channel.basicPublish(EXCHANGE_NAME,severity.getRoutingKey(),null,severity.getDetailMessage());
            } catch (IOException e) {
                System.out.println("[x] Sender failed to basic publish.");
            }
            catch (Exception e) {
                 e.printStackTrace();
            }

//            System.out.println("[x] Sender Sent " + severity.getRoutingKey() + " : " + new String(severity.getDetailMessage()));
        }
    }

    protected void finalize() throws IOException, TimeoutException {
        channel.close();
        connection.close();
    }

    private int BaseConnection(){

        /**
         * 创建连接连接到RabbitMQ
         */

        ConnectionFactory factory = new ConnectionFactory();
        //设置MabbitMQ所在主机ip或者主机名
        factory.setHost(IP);
        factory.setPort(Port);
        factory.setUsername(user);
        factory.setPassword(password);
        // 自动重连
        factory.setAutomaticRecoveryEnabled(true);

        //创建一个连接
        try {
            connection = factory.newConnection();
        } catch (IOException e) {
            System.out.println("[x] 请确认输入的IP地址、用户名、密码是否准确！");
            return  -1;
        } catch (TimeoutException e) {
            System.out.println("[x] 连接RabbitMQ超时，请重试！");
            return  -1;
        }

        //创建一个频道
        try {
            channel = connection.createChannel();
        } catch (IOException e) {
            System.out.println("[x] 创建频道出错，请重试！");
            return -1;
        }

        //声明一个路由器，指定名称、模式、及其是否durable
        try {
            channel.exchangeDeclare(EXCHANGE_NAME,EXCHANGE_TYPE,EXCHANGE_DURABLE);
        } catch (IOException e) {
            System.out.println("[x] 路由器声明失败，请重试！");
            return -1;
        }

        System.out.println("[x] 发布消息者成功连接至RabbitMQ !");

        return 0;

    }

}
